" key total
" search: <Leader>f+
" jump: <Leader>g+
" markdown: m+
" coc: c+
" other: <C>+

" let fmt = get(g:, 'plug_url_format', 'https://git::@hub.fastgit.org/%s.git') let plug.uri = substitute(plug.uri, '^http://git::@hub.fastgit\.org', 'https://hub.fastgit.org', '')

call plug#begin('~/.config/nvim/plugged')
" 这是vim-lsp的配置,和neovim-json区别开来
    " Plug 'prabirshrestha/vim-lsp'
    " Plug 'mattn/vim-lsp-settings'
" coc
    Plug 'neoclide/coc.nvim', {'branch': 'release'}
" align
    Plug 'junegunn/vim-easy-align'
" file sign
    Plug 'ryanoasis/vim-devicons'
" clang format
    Plug 'rhysd/vim-clang-format'
" convert traditional
    Plug 'jiazhoulvke/jianfan'
" commment
    " Plug 'tpope/vim-commentary'
    "commentary
    "https://github.com/preservim/nerdcommenter
    Plug 'preservim/nerdcommenter'
" vim cmd window
    Plug 'voldikss/vim-floaterm'
" db
    " Plug 'tpope/vim-dadbod'
    " Plug 'kristijanhusak/vim-dadbod-ui', { 'on': ['DBUI'] }
" blackets
    Plug 'luochen1990/rainbow'
" find
    " Plug 'Yggdroot/LeaderF', { 'do': ':LeaderfInstallCExtension' }
    Plug '/usr/local/opt/fzf'
    Plug 'junegunn/fzf.vim'
" translator
    Plug 'voldikss/vim-translator'
" markdown
    " Plug 'iamcco/markdown-preview.nvim', { 'do': 'cd app && yarn install'  }
     Plug 'ferrine/md-img-paste.vim'
    " Plug 'plasticboy/vim-markdown'
" color
    Plug 'guns/xterm-color-table.vim'
" compare tool
    Plug 'tpope/vim-fugitive'
" statusline
    Plug 'itchyny/lightline.vim'
" line, affect my view
    " Plug 'Yggdroot/indentLine'
" snippets
    Plug 'SirVer/ultisnips'
    Plug 'honza/vim-snippets'
" sandwich环绕字符编程
    Plug 'machakann/vim-sandwich'
"dart
    Plug 'dart-lang/dart-vim-plugin'

" symlink
    " Plug 'moll/vim-bbye' " optional dependency
    " Plug 'aymericbeaumet/vim-symlink'
" clang systax highlight
    " Plug 'jackguo380/vim-lsp-cxx-highlight'
call plug#end()

"Format <Clang Format>
    let g:clang_format#detect_style_file = 1
    let g:clang_format#auto_format=0
    let g:clange_format#command = "clang-format"
    " map to <Leader>cf in C++ code
    " autocmd FileType c,cpp,objc,objcpp nnoremap <buffer><silent>cf :<C-u>ClangFormat<CR>
    " autocmd FileType c,cpp,objc,objcpp vnoremap <buffer><silent>cf :ClangFormat<CR>
    " if you install vim-operator-user
    autocmd FileType c,cpp,objc,objcpp map <buffer><Leader>x <Plug>(operator-clang-format)

"EasyAlign
    xmap <Leader>al <Plug>(EasyAlign)
    nmap <Leader>al <Plug>(EasyAlign)
    let g:easy_align_delimiters ={
    \ '>':{'pattern':'>>\|=>\|>'},
    \ '-':{'pattern':'-->\|--\|->\|-'},
    \']': {
    \    'pattern':       '[[\]]',
    \    'left_margin':   0,
    \    'right_margin':  0,
    \    'stick_to_left': 0
    \  },
    \')': {
    \    'pattern':       '[()]',
    \    'left_margin':   0,
    \    'right_margin':  0,
    \    'stick_to_left': 0
    \  },
    \ '/':{
    \     'pattern':'//\+\|/\*\|\*/',
    \     'delimiter_align':'l',
    \     'ignore_groups':['!Comment']},
    \ }
"coc
" Use K to show documentation in preview window.
    function! s:show_documentation()
      if (index(['vim','help'], &filetype) >= 0)
        execute 'h '.expand('<cword>')
      elseif (coc#rpc#ready())
        call CocActionAsync('doHover')
      else
        execute '!' . &keywordprg . " " . expand('<cword>')
      endif
    endfunction
"CocCommand workspace.showOutput 检查命令输出
    let g:coc_status_error_sign='E:'
    let g:coc_status_warning_sign='W:'
    autocmd FileType c,cpp,objc,objcpp nnoremap <buffer><Leader>cf :call CocAction('format') <cr>
    autocmd FileType c,cpp,objc,objcpp xmap <Leader>f  <Plug>(coc-format-selected)
    autocmd FileType c,cpp,objc,objcpp nmap <Leader>f  <Plug>(coc-format-selected)
    " nnoremap <leader>cf :!swiftformat %<cr>
    nmap<silent> <leader>gd <Plug>(coc-definition)
    nmap<silent> <leader>gt <Plug>(coc-type-definition)
    nmap<silent> <leader>gi <Plug>(coc-implementation)
    nmap<silent> <leader>gr <Plug>(coc-references)
    nmap<silent> <leader>gh :call <SID>show_documentation()<CR>
    nmap<silent> <leader>cd :<c-u>CocList diagnostics<cr>
    nmap<silent> <leader>ce :<c-u>CocList extensions<cr>
    nmap<silent> <leader>ca :<c-u>CocAction<cr>
    nmap<silent> <leader>mh :CocCommand clangd.switchSourceHeader<Cr>
    nmap<silent> <Leader>rn <Plug>(coc-rename)
    function! s:check_back_space() abort
      let col = col('.') - 1
      return !col || getline('.')[col - 1]  =~ '\s'
    endfunction
    inoremap <silent><expr> <C-z>
          \ pumvisible() ? "\<C-n>" :
          \ <SID>check_back_space() ? "\<Tab>" :
          \ coc#refresh()
    inoremap <expr> <C-j> pumvisible() ? "\<Down>" : "\<C-j>"
    inoremap <expr> <C-k> pumvisible() ? "\<Up>" : "\<C-k>"
    " set completeopt +=select
    let g:coc_snippet_next = "<c-n>"
    let g:coc_snippet_prev = "<c-p>"
    " autocmd BufWritePre *.py silent! :call CocAction('runCommand', 'python.sortImports')
"coc.vim
    let g:coc_global_extensions=[
        \ 'coc-explorer',
        \ 'coc-db',
        \ 'coc-pairs',
        \ 'coc-vimlsp',
        \ 'coc-git',
        \ 'coc-pairs',
        \ 'coc-pyright',
        \ 'coc-json',
        \ 'coc-clangd',
        \ 'coc-tsserver',
        \ 'coc-webview',
        \ 'coc-markdownlint',
        \ 'coc-markdown-preview-enhanced',
        \ 'coc-sourcekit',
        \ 'coc-flutter'
        \ ]
" \ 'coc-markdownlint',

"coc.explorer
    let g:coc_explorer_global_presets = {
    \   '.vim': {
    \     'root-uri': '~/.vim',
    \   },
    \   'cocConfig': {
    \      'root-uri': '~/.config/coc',
    \   },
    \   'tab': {
    \     'position': 'tab',
    \     'quit-on-open': v:true,
    \   },
    \   'tab:$': {
    \     'position': 'tab:$',
    \     'quit-on-open': v:true,
    \   },
    \   'floating': {
    \     'position': 'floating',
    \     'open-action-strategy': 'sourceWindow',
    \   },
    \   'floatingTop': {
    \     'position': 'floating',
    \     'floating-position': 'center-top',
    \     'open-action-strategy': 'sourceWindow',
    \   },
    \   'floatingLeftside': {
    \     'position': 'floating',
    \     'floating-position': 'left-center',
    \     'floating-width': 50,
    \     'open-action-strategy': 'sourceWindow',
    \   },
    \   'floatingRightside': {
    \     'position': 'floating',
    \     'floating-position': 'right-center',
    \     'floating-width': 50,
    \     'open-action-strategy': 'sourceWindow',
    \   },
    \   'simplify': {
    \     'file-child-template': '[selection | clip | 1] [indent][icon | 1] [filename omitCenter 1]'
    \   },
    \   'buffer': {
    \     'sources': [{'name': 'buffer', 'expand': v:true}]
    \   },
    \ }
    nnoremap <Leader>e :CocCommand explorer --preset floating<cr>
    au User CocExplorerOpenPre  hi Pmenu ctermbg=NONE
    au User CocExplorerQuitPost hi Pmenu ctermbg=238
    au User CocExplorerQuitPost echo
    
" coc-git
    nmap     <silent>       (         <Plug>(coc-git-prevchunk)
    nmap     <silent>       )         <Plug>(coc-git-nextchunk)
    vmap     <silent>       ig        <Plug>(coc-git-chunk-inner)
    vmap     <silent>       ag        <Plug>(coc-git-chunk-outer)
    " nmap     <silent><expr> C         get(b:, 'coc_git_blame', '') ==# 'Not committed yet' ? "<Plug>(coc-git-chunkinfo)" : "<Plug>(coc-git-commit)"
    " nmap     <silent>       <leader>g :call coc#config('git.addGBlameToVirtualText',  !get(g:coc_user_config, 'git.addGBlameToVirtualText', 0))<cr>

"coc-snippet
    " nmap <silent>gs :CocCommand snippets.openSnippetFiles<cr>
    " let g:coc_snippet_next = '<c-n>'
    " let g:coc_snippet_prev = '<c-p>'
    " imap <C-n> <Plug>(coc-snippets-expand-jump)
"ultisnips
    let g:UltiSnipsExpandTrigger="<c-n>"
    let g:UltiSnipsJumpForwardTrigger="<c-p>"
    let g:UltiSnipsJumpBackwardTrigger="<c-n>"
    " let g:UltiSnipsEditSplit="vertical"
    let g:UltiSnipsSnippetDirectories=['~/.config/nvim/ultisnips']
"vim-markdown
    " let g:tex_conceal = ""
    " let g:vim_markdown_math = 1
    " let g:vim_markdown_folding_disabled = 1
    " let g:vim_markdown_conceal_code_blocks = 0
    " let g:vim_markdown_conceal = 0
    " let g:vim_markdown_strikethrough = 1
"floaterm
    let g:floaterm_title = ''
    let g:floaterm_width = 0.6
    let g:floaterm_height = 0.8
    let g:floaterm_autoclose = 1
    nnoremap   <silent>   <F9>    :FloatermNew<CR>
    tnoremap   <silent>   <F9>    <C-\><C-n>:FloatermNew<CR>
    nnoremap   <silent>   <F10>   :FloatermPrev<CR>
    tnoremap   <silent>   <F10>   <C-\><C-n>:FloatermPrev<CR>
    nnoremap   <silent>   <F11>   :FloatermNext<CR>
    tnoremap   <silent>   <F11>   <C-\><C-n>:FloatermNext<CR>
    nnoremap   <silent>   <F12>   :FloatermToggle<CR>
    tnoremap   <silent>   <F12>   <C-\><C-n>:FloatermToggle<CR>

"db
    " let g:db_ui_save_location = '~/.config/db'
    " let g:db_ui_use_nerd_fonts = 1
    " let g:db_ui_force_echo_notifications = 1
    " let g:db_ui_table_helpers = {
    " \   'mysql': {
    " \     'List': 'SELECT * from `{schema}`.`{table}` order by id desc LIMIT 100;',
    " \     'Indexes': 'SHOW INDEXES FROM `{schema}`.`{table}`;',
    " \     'Table Fields': 'DESCRIBE `{schema}`.`{table}`;',
    " \     'Alter Table': 'ALTER TABLE `{schema}`.`{table}` ADD '
    " \   }
    " \ }
    " let g:db_ui_locked = 0
    " com! CALLDB call DBUI()
    " func DBUI()
    "     let g:db_ui_locked = 1
    "     set laststatus=0 showtabline=0 nonu signcolumn=no nofoldenable
    "     exec 'DBUI'
    " endf
    " func DBUIToggle()
    "     if floaterm#terminal#get_bufnr('DBUI') < 0
    "         exec 'FloatermNew --name=DBUI nvim +CALLDB'
    "     else
    "         exec 'FloatermToggle DBUI'
    "     endif
    " endf
    " nnoremap <silent><expr> <c-b> g:db_ui_locked ? "" : ":call DBUIToggle()<CR>"
    " tnoremap <silent><expr> <c-b> &ft == "floaterm" ? "<c-\><c-n>:call DBUIToggle()<CR>" : "<c-b>"

" rainbow
    let g:rainbow_active = 1
    let g:rainbow_conf = {'ctermfgs': ['lightblue', 'lightyellow', 'lightcyan', 'lightmagenta', 'blue', 'yellow', 'cyan', 'magenta']}
" fzf
    "所有buffer搜索文件
    noremap <Leader>fb :Buffers<CR>
    "工作目录搜索语法关键字
    noremap <Leader>fg :Tags<cr>
    "当前buffer搜索语法关键字
    noremap <Leader>ft :BTags<CR>
    "当前buffer搜索string
    noremap <Leader>fl :BLines<CR>
    "所有buffer搜索string
    noremap <Leader>fa :Lines<CR>
    "工作目录搜索文件
    noremap <Leader>ff :FZF<CR>
    "工作目录搜索字符
    noremap <Leader>fs :Rg<cr>

" <Leaderf,leaderf,Leaderf>
" 不怎么友好支持objc, 使用outline吧
    "let g:Lf_DefaultMode = 'NameOnly'
    "let g:Lf_ShowRelativePath = 1
    "let g:Lf_PopupShowFoldcolumn = 0
    "let g:Lf_HideHelp = 1
    "let g:Lf_UseCache = 0
    "let g:Lf_UseMemoryCache = 0
    "let g:Lf_UseVersionControlTool = 0
    "let g:Lf_IgnoreCurrentBufferName = 1
    "let g:Lf_WindowPosition = 'popup'
    "let g:Lf_PopupWidth = 0.6
    "let g:Lf_PopupHeight = 0.8
    "let g:Lf_PreviewInPopup = 1
    "let g:Lf_StlSeparator = { 'left': "\ue0b0", 'right': "\ue0b2", 'font': "DejaVu Sans Mono for Powerline" }
    "let g:Lf_PreviewResult = {
    "        \ 'File': 0,
    "        \ 'Buffer': 0,
    "        \ 'Mru': 0,
    "        \ 'Tag': 0,
    "        \ 'BufTag': 0,
    "        \ 'Function': 0,
    "        \ 'Line': 0,
    "        \ 'Colorscheme': 0,
    "        \ 'Rg': 0,
    "        \ 'Gtags': 0
    "        \}
    "let g:Lf_SpinSymbols = ['△', '▲', '▷', '▶', '▽', '▼', '◁', '◀']
    "let g:Lf_GtagsAutoGenerate = 0 " should use `Leaderf gtags --update` first
    "let g:Lf_GtagsAutoUpdate = 0
    "let g:Lf_Gtagslabel = 'native-pygments'
    "let g:Lf_ShowHidden = 1
    "let g:Lf_ShowDevIcons = 1
    "let g:Lf_DevIconsFont = "DroidSansMono Nerd Font Mono"
    "let g:Lf_RootMarkers = ['session.viminfo', 'session.vim']
    """搜索buffer
    "noremap <Leader>fb :Leaderf buffer<CR>
    "noremap <Space>b :None<CR>
    """搜索最近使用过的文件( search most recently used files)就是Mru
    "noremap <Leader>fm :Leaderf mru<CR>
    """当前buffer搜索function，var
    "noremap <Leader>ft :Leaderf function --nowrap<CR>
    """当前buffer搜索string
    "noremap <Leader>fl :LeaderfLine<CR>
    """所有buffer搜索string
    "noremap <Leader>fa :LeaderfLineAll<CR>
    """工作目录搜索文件
    "noremap <Leader>ff :Leaderf file<CR>
    "noremap <Leader>f :None<CR>
    """工作目录搜索字符
    "noremap <Leader>fr :Leaderf rg<cr>
    """工作目录搜索function
    "" noremap fg :Leaderf <cr>
    "let g:Lf_NormalMap = {
	    "\ "File":   [["<ESC>", ':exec g:Lf_py "fileExplManager.quit()"<CR>']],
	    "\ "Buffer": [["<ESC>", ':exec g:Lf_py "bufExplManager.quit()"<CR>']],
	    "\ "Mru":    [["<ESC>", ':exec g:Lf_py "mruExplManager.quit()"<CR>']],
	    "\ "Tag":    [["<ESC>", ':exec g:Lf_py "tagExplManager.quit()"<CR>']],
	    "\ "Function":    [["<ESC>", ':exec g:Lf_py "functionExplManager.quit()"<CR>']],
    "    \ "Rg":     [["<ESC>", ':exec g:Lf_py "rgExplManager.quit()"<CR>']],
	    "\ "Colorscheme":    [["<ESC>", ':exec g:Lf_py "colorschemeExplManager.quit()"<CR>']],
	    "\ }
    "let g:Lf_CommandMap = {'<C-X>': ['<F5>'], '<C-]>': ['<F6>']}
    "highlight Lf_hl_popup_window guifg=#eeeeee guibg=#080808 gui=NONE ctermfg=255 ctermbg=232 cterm=NONE
    "highlight Lf_hl_popup_inputText guifg=#87ceeb guibg=#080808 gui=NONE ctermfg=117 ctermbg=232 cterm=NONE
    "highlight def Lf_hl_popup_blank guifg=NONE guibg=#080808 gui=NONE ctermbg=232 cterm=NONE
    "" let g:Lf_CtagsFuncOpts = {
    ""         \ 'c': '--c-kinds=fp',
    ""         \ 'rust': '--rust-kinds=f',
    ""         \ 'objc': '--objc-kinds=fp',
    ""         \ }
"traslator
    let g:translator_default_engines=['sdcv', 'bing','youdao']
    nmap <silent>t <Plug>TranslateW
    vmap <silent>t <Plug>TranslateWV
    let g:translator_history_enable=v:true
"iamcco/markdown-preview md-img-paste
    "let g:mkdp_refresh_slow = 1
    "let g:mkdp_browser = '/Applications/Safari.app'
    "let g:mkdp_theme = 'light'
    "nmap <Leader>mp <Plug>MarkdownPreview<cr>
    "nmap <Leader>ms <Plug>MarkdownPreviewStop<cr>
    autocmd FileType markdown nmap<buffer><silent> <Leader>mi :call mdip#MarkdownClipboardImage()<CR>
    "生成md的嵌入图片代码"
    autocmd FileType markdown nmap<silent> cs :call ConvertString()<CR>
    function ConvertString()
        let l:lineContent = getline(line('.'))
        let l:line = matchlist(l:lineContent, '\v\!\[(.*)\]\((.*)\)')
        let l:name = l:line[1]
        let l:path = l:line[2]
        let l:replaceContent = "<div align=\"center\"><img src=\"" . l:path . "\" alt=\"" . l:name . "\" style=\"zoom:%;\" width=200 height=300/><\/div>"
        execute "normal! 0v$s".l:replaceContent
    endfunction
"commment
    " xmap cm  <Plug>Commentary
    " nmap cm  <Plug>Commentary
    " omap cm  <Plug>Commentary
    " nmap cm  <Plug>CommentaryLine
    " " if maparg('c','n') ==# '' && !exists('v:operator')
    " "   nmap cm <Plug>ChangeCommentary
    " " endif
    " autocmd FileType apache setlocal commentstring=#\ %s
"statusline
    let g:lightline = {
          \ 'colorscheme': 'landscape',
          \ 'active': {
          \     'left': [['mode', 'paste'], ['readonly', 'filename', 'modified'], ['coc', 'fugitive']],
          \ },
          \ 'component': {
          \   'coc': '%{coc#status()}',
          \    'fugitive':'%{FugitiveStatusline()}'
          \ },
          \ 'mode_map': {
          \ 'n' : 'N',
          \ 'i' : 'I',
          \ 'R' : 'R',
          \ 'v' : 'V',
          \ 'V' : 'VL',
          \ "\<C-v>": 'VB',
          \ 'c' : 'C',
          \ 's' : 'S',
          \ 'S' : 'SL',
          \ "\<C-s>": 'SB',
          \ 't': 'T',
          \ },
          \ }
"line
    " let g:indentLine_char = '┊'
"systax
    let g:python_highlight_all = 1
"sandwich环绕字符编程
    let g:operator_sandwich_no_default_key_mappings = 1
    let g:sandwich_no_default_key_mappings = 1
	nmap s <Nop>
	xmap s <Nop>
	omap s <Nop>
    " add
    " <unique>, 不要加，重载会有映射失败的log，影响界面, 但是不影响运行
    nmap sa <Plug>(operator-sandwich-add)
    xmap sa <Plug>(operator-sandwich-add)
    omap sa <Plug>(operator-sandwich-g@)
    " delete
    xmap sd <Plug>(operator-sandwich-delete)
    " replace
    xmap sr <Plug>(operator-sandwich-replace)
    nmap sd <Plug>(operator-sandwich-delete)<Plug>(operator-sandwich-release-count)<Plug>(textobj-sandwich-query-a)
    nmap sr <Plug>(operator-sandwich-replace)<Plug>(operator-sandwich-release-count)<Plug>(textobj-sandwich-query-a)
    nmap sdb <Plug>(operator-sandwich-delete)<Plug>(operator-sandwich-release-count)<Plug>(textobj-sandwich-auto-a)
    nmap srb <Plug>(operator-sandwich-replace)<Plug>(operator-sandwich-release-count)<Plug>(textobj-sandwich-auto-a)
"vim-fugitive
"Git: info

" 这是vim-lsp的配置,和neovim-json区别开来
" vim-lsp没有完全研究，此处不能用
" if executable('/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/sourcekit-lsp')
"     au User lsp_setup call lsp#register_server({
"         \ 'name': '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/sourcekit-lsp',
"         \ 'cmd': {server_info->['/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/sourcekit-lsp']},
"         \ 'whitelist': ['swift'],
"         \ })
" endif

" augroup filetype
"   au! BufRead,BufNewFile *.swift set ft=swift

" coc-markdown-preview-enhanced coc-markdownlint coc-webview
" shortcut
nnoremap <Leader>md :CocList --input=markdown-preview-enhanced. commands<cr>

"swiftFormat
"brew install swiftformat
autocmd FileType swift nnoremap <buffer><Leader>cf :!swiftformat --swiftversion 5.7 .<cr>

"preservim/nerdcommenter
"nmap cm  <leader>c<space>
"[count]<leader>cc |NERDCommenterComment|
"Comment out the current line or text selected in visual mode.
"
"[count]<leader>cn |NERDCommenterNested|
"Same as cc but forces nesting.
"
"[count]<leader>c<space> |NERDCommenterToggle|
"Toggles the comment state of the selected line(s). If the topmost selected line is commented, all selected lines are uncommented and vice versa.
"
"[count]<leader>cm |NERDCommenterMinimal|
"Comments the given lines using only one set of multipart delimiters.
"
"[count]<leader>ci |NERDCommenterInvert|
"Toggles the comment state of the selected line(s) individually.
"
"[count]<leader>cs |NERDCommenterSexy|
"Comments out the selected lines with a pretty block formatted layout.
"
"[count]<leader>cy |NERDCommenterYank|
"Same as cc except that the commented line(s) are yanked first.
"
"<leader>c$ |NERDCommenterToEOL|
"Comments the current line from the cursor to the end of line.
"
"<leader>cA |NERDCommenterAppend|
"Adds comment delimiters to the end of line and goes into insert mode between them.
"
"|NERDCommenterInsert|
"Adds comment delimiters at the current cursor position and inserts between. Disabled by default.
"
"<leader>ca |NERDCommenterAltDelims|
"Switches to the alternative set of delimiters.
"
"[count]<leader>cl |NERDCommenterAlignLeft [count]<leader>cb |NERDCommenterAlignBoth
"Same as |NERDCommenterComment| except that the delimiters are aligned down the left side (<leader>cl) or both sides (<leader>cb).
"
"[count]<leader>cu |NERDCommenterUncomment|
"Uncomments the selected line(s).
